package xuanzhen.manage.controller;

import java.io.UnsupportedEncodingException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTCreatorTest;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;

import net.sf.json.JSONObject;
import xuanzhen.reservation.pojo.BlackUser;
import xuanzhen.reservation.pojo.PostMan;
import xuanzhen.reservation.pojo.RedPacket;
import xuanzhen.reservation.pojo.Reservation;
import xuanzhen.reservation.service.BlackUserService;
import xuanzhen.reservation.service.PostManService;
import xuanzhen.reservation.service.RedPacketService;
import xuanzhen.reservation.service.ReservationService;
import xuanzhen.wx.util.WeixinUtil;

@Controller
@RequestMapping("/resManage")
public class ReChickController {
	@Resource
	private PostManService postmanService;
	@Resource
	private ReservationService reservationService;
	@Resource
	private RedPacketService redPacketService;
	@Resource
	private BlackUserService blackUserService;
	/**
	 * 小鸡进入
	 */
	@RequestMapping(value = "/open.html", method = RequestMethod.GET)
	public String show(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	
			return "reservation/login";
	}
	/**
	 * 小鸡登录
	 */
	@RequestMapping(value = "/signIn.html", method = RequestMethod.POST)
	public String sign(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,PostMan postman)
			throws Exception {
		List<PostMan> posList=postmanService.queryListByEntity(postman);
		if(posList.isEmpty()){
			model.addAttribute("states","登录名有误");
			return "reservation/login";
		}
		Map<String,Object> parameter = new HashMap<String,Object>();
		parameter.put("pId", posList.get(0).getId());
		model.addAttribute("pId",posList.get(0).getId());
		parameter.put("state", "UNFINISH");
		int unfCount = reservationService.countUnDeul(parameter);
		int pageSum = 0;
		if(unfCount%10==0){
			pageSum = unfCount/10;
		}else{
			pageSum = unfCount/10+1;
		}
		model.addAttribute("pageSum",pageSum);
		//完成任务页数
		parameter.put("state", "FINISH");
		int fCount = reservationService.countUnDeul(parameter);
		int pageSum2 = 0;
		if(fCount%10==0){
			pageSum2 = fCount/10;
		}else{
			pageSum2 = fCount/10+1;
		}
		model.addAttribute("pageSum2",pageSum2);
		return "reservation/index";
	}
	@RequestMapping(value = "/index.html", method = RequestMethod.GET)
	public String ind(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	
			return "reservation/index";
	}
	
	/**
	 * 小鸡任务显示
	 */
	@RequestMapping(value = "/showList", method = RequestMethod.POST)
	@ResponseBody
	public Object showList(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("id")int id,@Param("pageIndex") Integer pageIndex)
			throws Exception {
		Map<String,Object> parameter = new HashMap<String,Object>();
		parameter.put("pId", id);
		parameter.put("state", "UNFINISH");
		parameter.put("pageBegin", pageIndex*10);
		parameter.put("pageSize", 10);
		List<Reservation> resList = reservationService.queryListByMap(parameter);
		
		
			return resList;
	}
	/**
	 * 小鸡完成任务显示
	 */
	@RequestMapping(value = "/showFinishList", method = RequestMethod.POST)
	@ResponseBody
	public Object showFinishList(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("id")int id,@Param("pageIndex") Integer pageIndex)
			throws Exception {
		Map<String,Object> parameter = new HashMap<String,Object>();
		parameter.put("pId", id);
		parameter.put("state", "FINISH");
		parameter.put("pageBegin", pageIndex*10);
		parameter.put("pageSize", 10);
		List<Reservation> resList = reservationService.queryListByMap(parameter);
		
			return resList;
	}
	/**
	 * 小鸡完成
	 */
	@RequestMapping(value = "/finis.html", method = RequestMethod.POST)
	public void finis(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("rid") int rid,@Param("phone") String phone)
			throws Exception {
		Reservation reservation = new Reservation();
		reservation.setId(rid);
		reservation.setState("FINISH");
		//createTime
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
				String nowTime = dateFormat.format(now);
				ParsePosition pos = new ParsePosition(0);
				Date currentTime_2 = dateFormat.parse(nowTime, pos);
		reservation.setFinishTime(currentTime_2);
		reservation.setRedsCount(0);
		int tag = reservationService.updateReservation(reservation);
		//确认完成发放红包
		//createTime
	/*	Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		ParsePosition pos = new ParsePosition(0);
		Date currentTime_2 = dateFormat.parse(nowTime, pos);*/
		List<Reservation> res = reservationService.queryListByEntity(reservation);
		String unique = res.get(0).getPhone();
		RedPacket reds = new RedPacket();
		reds.setRid(rid);
		reds.setName("约车红包"+System.currentTimeMillis()/1000);
		reds.setUnique(unique);
		reds.setCount(9);
		String begin = JWTCreatorTest.getSecondTimes();
		reds.setBegin(begin);
		reds.setExpiry(7);
		int iat = (int)(System.currentTimeMillis()/1000-30);
		reds.setIat(iat);
		int exp = (int)(System.currentTimeMillis()/1000+300);
		reds.setExp(exp);
		reds.setCreateTime(currentTime_2);
		reds.setDeleteState(1);
		Map<String, Object> header = new HashMap<String, Object>();
        header.put("typ", "JWT");
        String signed = JWTCreator.init()
                .withHeader(header)
                .withClaim("unique", reds.getUnique())
                .withClaim("name", reds.getName())
                .withClaim("count", reds.getCount())
                .withClaim("begin", reds.getBegin())
                .withClaim("expiry", reds.getExpiry())
                .withClaim("iat", reds.getIat())
                .withClaim("exp", reds.getExp())
                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
        
        System.out.println("https://wechat.car2go.cn/coupon/get/?jwt="+signed);
        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/get/?jwt="+signed,"GET",null);
		System.out.println(js);
		if("\"success\"".equals(js)){
		redPacketService.insertRedPacket(reds);
			}

		
	}
	public static void main(String[] args) throws IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		//确认完成发放红包
				Map<String, Object> header = new HashMap<String, Object>();
		        header.put("typ", "JWT");
		        String signed = JWTCreator.init()
		                .withHeader(header)
		                .withClaim("unique", "+8615637915222")
		                .withClaim("name", "测试红包上传1")
		                .withClaim("count", 8)
		                .withClaim("begin", JWTCreatorTest.getSecondTimes())
		                .withClaim("expiry", 7)
		                .withClaim("iat", (int)(System.currentTimeMillis()/1000-30))
		                .withClaim("exp", (int)(System.currentTimeMillis()/1000+300))
		                .sign(Algorithm.HMAC256("5DC5F734E2568A53AA9C1279D1B96"));
		        
		        System.out.println("https://wechat.car2go.cn/coupon/get/?jwt="+signed);
		        String js= WeixinUtil.redhttpsRequest("https://wechat.car2go.cn/coupon/get/?jwt="+signed,"GET",null);
				System.out.println(js);
	}
	/**
	 * 小鸡取消
	 */
	@RequestMapping(value = "/beicancel.html", method = RequestMethod.POST)
	@ResponseBody
	public String cancel(Model model, HttpSession session, HttpServletRequest request, HttpServletResponse response,@Param("rid") int rid,@Param("phone") String phone,@Param("cancelFeedback") String cancelFeedback)
			throws Exception {
		Reservation reservation = new Reservation();
		reservation.setId(rid);
		reservation.setState("BEICANCEL");
		//createTime
		Date now = new Date();
		SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// 可以方便地修改日期格式
		String nowTime = dateFormat.format(now);
		ParsePosition pos = new ParsePosition(0);
		Date currentTime_2 = dateFormat.parse(nowTime, pos);
		reservation.setFinishTime(currentTime_2);
		reservation.setCancelTime(currentTime_2);
		reservation.setCancelFeedback(cancelFeedback);
		int tag = reservationService.updateReservation(reservation);
		Reservation reCondition=new Reservation();
		reCondition.setId(rid);
		List<Reservation> res = reservationService.queryListByEntity(reCondition);
		insertBlackUserByIllegal(res.get(0));
		
		return "success";
	}
	public void insertBlackUserByIllegal(Reservation reser) throws Exception{
		/*Reservation re = new Reservation();
		re.setPhone(reser.getPhone());
		re.setState("BEICANCEL");*/
	/*	int tags = reservationService.selectCountIllegalChick(re);*/
		BlackUser blackUser = new BlackUser();
		blackUser.setBlackPhone(reser.getPhone());
		blackUser.setBlackDeleteState(2);
		blackUser.setBlackBeginTime(new Date());
		/*if(tags ==2){
			Date da = blackUser.getBlackBeginTime();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(da);
			calendar.add(Calendar.DATE, 7);
			blackUser.setBlackEndTime(calendar.getTime());
		}else if(tags>=3){
			Date da = blackUser.getBlackBeginTime();
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(da);
			calendar.add(Calendar.YEAR,100 );
			blackUser.setBlackEndTime(calendar.getTime());
		}*/
		int w = blackUserService.insertBlackUser(blackUser);
		
	}
}
